終於解完程式碼問題了,可以開始講解了。
上一期,我們成功讓按鈕連結到我們的遊戲邏輯程式碼。
每點按一次,遊戲物件的屬性面板中,CurrentState的狀態就會改變。
這次,我們要:
首先,打開程式碼。
檢查之後,我們需要
(第三個)
同時,我們還需要
若是一直重複檢查、重複賦予變數值的話,會很耗費遊戲的運算資源。
所以我們在上圖也新增了GameStateChanged布林變數。
在遊戲一開始會觸發的Start()函式中,因為初始化GameState為MainMenu,
畢竟我們要改變狀態了。
這樣可能會導致Race Condition,畢竟不知道會不會該行運行到一半,切回到Update()。
然後又被設定回False。
然後回來繼續執行時,狀態改了。
但是什麼都沒改到,因為在檢查時,他看布林值是False,以為沒變!
(也有可能Unity不會發生這種事,我想多了。但是這樣撰寫邏輯比較順暢。
然後回到Update(),把剛剛說的:
到最後整體程式碼會長這樣:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public enum GameState
{
MainMenu,
SelectGameMode,
Playing,
GameOver,
// Add more states as needed
}
public class GameStateManager : MonoBehaviour
{
public GameState currentState;
public GameObject Card;
public TMP_Text GameModeText;
public bool GameStateChanged;
// Start is called before the first frame update
void Start()
{
currentState = GameState.MainMenu; // Set your initial state
GameStateChanged = true;
}
void Update()
{
if (GameStateChanged)
{
Debug.Log(currentState);
GameStateChanged = false;
GameModeText.text = currentState.ToString();
}
switch (currentState)
{
case GameState.MainMenu:
// Handle logic for the main menu state
break;
case GameState.SelectGameMode:
// Handle logic for the selecting game mode state
break;
case GameState.Playing:
// Handle logic for the playing state
break;
case GameState.GameOver:
// Handle logic for the game over state
break;
// Add more cases as needed
}
}
public void StartGame()
{
currentState = GameState.Playing;
}
public void OnStartButtonClicked()
{
StartGame(); // This method will change the game state to Playing
}
public void SequentialChangeGameState()
{
switch (currentState)
{
case GameState.MainMenu:
currentState = GameState.SelectGameMode;
// Handle logic for the main menu state
break;
case GameState.SelectGameMode:
currentState = GameState.Playing;
// Handle logic for the selecting game mode state
break;
case GameState.Playing:
currentState = GameState.GameOver;
// Handle logic for the playing state
break;
case GameState.GameOver:
currentState = GameState.MainMenu;
// Handle logic for the game over state
break;
// Add more cases as needed
}
GameStateChanged = true;
}
}
然後儲存,我們測試吧!
那下一期我們來講解,撰寫程式期間會遭遇怎麼樣的危機,以及如何解決。